import React                    from 'react';
import {connect}                from "react-redux";

import PullUp                   from '../../components/form/PullUp';
import CartCount                from '../../components/form/CartCount';
import Pagination               from '../../components/Pagination';
import {Token}                  from "../../utils/Storage";
import {userInfo}               from '../../actions/active';
import {TicketHead, TicketFoot} from '../main/Voucher';
import {
    edit,
    loadList,
    loadItem,
}                               from "../../actions/cart";
import './list.scss';

function formatTime(time, format) {
    const dateTime = new Date(time);
    const o = {
        'M+': dateTime.getMonth() + 1, // month
        'd+': dateTime.getDate(), // day
        'h+': dateTime.getHours(), // hour
        'm+': dateTime.getMinutes(), // minute
        's+': dateTime.getSeconds(), // second
        'q+': Math.floor((dateTime.getMonth() + 3) / 3), // quarter
        S: dateTime.getMilliseconds(), // millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1,
            (`${dateTime.getFullYear()}`).substr(4 - RegExp.$1.length));
    }
    for (const k in o) {
        if (new RegExp(`(${k})`).test(format)) {
            format = format.replace(RegExp.$1,
                RegExp.$1.length === 1 ? o[k] :
                (`00${o[k]}`).substr((`${o[k]}`).length));
        }
    }
    return format;
}
export class List extends Pagination {

    state = {list: [], openId: ''};

    _method = () => 'loadList';

    componentWillMount(){
        this.load();
        if(Token.isActive()){
            this.updateCount();
            this.props.userInfo();
        }
    }

    toggle(id){
        this.setState({openId: this.state.openId === id ? '' : id});
    }

    updateCount(){
        this.props.loadItem();
        return true;
    }

    getTotal(){
        return this.props.item.list.reduce((t, i) => t += i.exchangeCount * i.accumulate, 0);
    }

    getSingleTotal(m){
        var item = _.find(this.props.item.list, {id: m.id});
        return item ? item.accumulate * (item.exchangeCount || 1) : m.accumulate;
    }

    isSellout(m){
        return m.count < m.exchangeCount;
    }

    add(m, count){
        if(m.count < count){
            this.alert('库存不足');
            return Promise.resolve(false);
        }
        if(this.props.user.accumulate < this.getTotal()){
            this.alert('积分不足');
            return Promise.resolve(false);
        }
        return this.props.edit(Object.assign({}, m, {count})).then(this.updateCount.bind(this));
    }

    minus(m, count){
        return this.props.edit(Object.assign({}, m, {count})).then(this.updateCount.bind(this));
    }

    render(){
        var {list, openId} = this.state;
        return (
            <PullUp load={this.reload.bind(this)} className="c-list">
                {list.map(m => {
                    var isSellout = this.isSellout(m);
                    return (
                        <div key={m.id} className="ticket">
                            <div className="tic-body" ref={`item${m.id}`}>
                                <TicketHead item={m} className={isSellout ? 'stamp-red' : undefined}/>
                                <div className="tic-right flex-avg">
                                    <div className="tic-detail" onClick={() => this.toggle(m.id)}>
                                        <div className="tic-d-name">{m.name}</div>
                                        <div className="tic-d-text">
                                            <div>{m.limitPrice}</div>
                                            {/^[1-9]\d*$/.test(m.limitConsume) ? `消费满${m.limitConsume}元可用` : '详细信息'}
                                            <span className={`tic-d ${openId === m.id ? ' open' : ''}`}>▲</span>
                                        </div>
                                        <div className="tic-time"><span>兑换截止：</span>{formatTime(m.expire,'yyyy-MM-dd')}</div>
                                    </div>
                                    <div
                                        onClick={() => this.toggle(m)}
                                        className={`tic-cart flex-avg${isSellout ? ' sellout' : ''}`}
                                    >
                                        <div>需要积分</div>
                                        <div>{this.getSingleTotal(m)}</div>
                                        <CartCount
                                            value={m.exchangeCount}
                                            target={() => this.refs[`item${m.id}`]}
                                            beforeAdd={c => this.add(m, c)}
                                            beforeMinus={c => this.minus(m, c)}
                                        />
                                        {isSellout && <div>库存不足</div>}
                                    </div>
                                </div>
                            </div>
                            <div className={`using${m.id === openId ? '' : ' hide'}`}>
                                <div className="vu-title">{m.name}</div>
                                <div className="vu-title">{m.limitPrice}</div>
                                <TicketFoot item={m}/>
                            </div>
                        </div>
                    );
                })}
            </PullUp>
        );
    }

}

const mapStateToProps = state => ({
    item: state.cart.item,
    user: state.active.get,
});

export default connect(mapStateToProps, {edit, loadItem, loadList, userInfo})(List);
